package com.sjb.training.lc;

/**
 * Created with IntelliJ IDEA.
 * lc.59 螺旋矩阵
 *
 * @Author: 有点儿意思
 * @Description:
 */
public class GenerateMatrix {
    public static void main(String[] args) {
        int n = 3;
        int[][] ints = generateMatrix(n);
        for (int[] anInt : ints) {
            for (int i : anInt) {
                System.out.println(i);
            }
        }
    }

    public static int[][] generateMatrix(int n) {
        int[][] nums = new int[n][n];
        int startX = 0, startY = 0; // 每一圈的起始点
        int i, j;
        int offset = 1;
        int count = 1; // 矩阵中需要填写的数字
        int loop = 1; //记录当前的圈数
        while (loop <= n / 2) {
            // 遍历顶部
            for (j = startY; j < n - offset; j++) {
                nums[startX][j] = count++;
            }
            // 遍历右部
            for (i = startX; i < n - offset; i++) {
                nums[i][j] = count++;
            }
            // 遍历下部
            for (; j > startY; j--) {
                nums[i][j] = count++;
            }
            // 遍历左部
            for (; i > startX; i--) {
                nums[i][j] = count++;
            }
            startX++;
            startY++;
            offset++;
            loop++;
        }
        if (n % 2 == 1) {
            // n为奇数
            nums[startX][startY] = count;
        }
        return nums;
    }

}
